package com.lew.jlight.web.exception.handler;

import com.lew.jlight.core.Response;
import com.lew.jlight.core.util.JsonUtil;
import com.lew.jlight.web.util.ServletUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice()
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(RuntimeException.class)
    public void exceptionHandler(Exception e) {
        HttpServletResponse httpServletResponse = ServletUtil.getResponse();
        Response resp = new Response();
        resp.setCode(-1);
        if (e instanceof NullPointerException || e instanceof IllegalArgumentException || e instanceof
                IndexOutOfBoundsException) {
            String errorMsg = e.getMessage();
            if (errorMsg.contains(":")) {
                errorMsg = errorMsg.split(":")[1];
            }
            resp.setMsg(errorMsg);
        } else {
            resp.setMsg("服务繁忙,请联系管理员");
        }
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = httpServletResponse.getWriter();
            out.append(JsonUtil.parseObject2Str(resp));
            out.flush();
        } catch (IOException ioe) {
            logger.error("failed to parse response to json by response={}", resp);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        logger.error("invoke jlight had error!", e);
    }

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
            ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
            container.addErrorPages(error401Page, error404Page, error500Page);
        });
    }
}
